﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataHelper.cs" company="">
//   
// </copyright>
// <summary>
//   The data helper.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WisdriContacts.Model
{
    using Windows.Storage;

    /// <summary>
    /// The data helper.
    /// </summary>
    public class DataHelper
    {
        /// <summary>
        /// The sqlite db file path.
        /// </summary>
        public static readonly string DB_PATH =
            Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "contacts.db"));

        /// <summary>
        /// The move reference database.
        /// </summary>
        public static async void MoveReferenceDatabase()
        {
            StorageFile dbFile = null;
            try
            {
                // Try to get the 
                dbFile = await StorageFile.GetFileFromPathAsync(DB_PATH);
            }
            catch (FileNotFoundException)
            {
                if (dbFile == null)
                {
                    // Copy file from installation folder to local folder.
                    // Obtain the virtual store for the application.
                    IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();

                    // Create a stream for the file in the installation folder.
                    using (Stream input = Application.GetResourceStream(new Uri("contacts.db", UriKind.Relative)).Stream
                        )
                    {
                        // Create a stream for the new file in the local folder.
                        using (IsolatedStorageFileStream output = iso.CreateFile(DB_PATH))
                        {
                            // Initialize the buffer.
                            byte[] readBuffer = new byte[4096];
                            int bytesRead = -1;

                            // Copy the file from the installation folder to the local folder. 
                            while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
                            {
                                output.Write(readBuffer, 0, bytesRead);
                            }
                        }
                    }
                }
            }
        }
    }
}